package com.google.code.swingonfire.utility.date;

import java.text.DateFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import com.google.code.swingonfire.utility.Tokenizer.Token;

/**
 * Holds information, how a date should get rendered
 * 
 * @author thred
 */
public class DateRenderInfo
{

    private final List<DateRenderInfoPart> parts;

    public DateRenderInfo(String pattern)
    {
        this(parse(pattern));
    }

    public DateRenderInfo(List<DateRenderInfoPart> parts)
    {
        super();

        this.parts = Collections.unmodifiableList(parts);
    }

    public String format(Calendar calendar)
    {
        return format(calendar, Locale.getDefault());
    }

    public String format(Calendar calendar, Locale locale)
    {
        return format(calendar, DateFormatSymbols.getInstance(locale), locale);
    }

    public String format(Calendar calendar, DateFormatSymbols dateFormatSymbols, Locale locale)
    {
        StringBuilder builder = new StringBuilder();

        for (DateRenderInfoPart part : parts)
        {
            part.format(builder, calendar, dateFormatSymbols, locale);
        }

        return builder.toString();
    }

    private static List<DateRenderInfoPart> parse(String pattern)
    {
        List<DateRenderInfoPart> parts = new ArrayList<DateRenderInfoPart>();
        DateRenderInfoTokenizer tokenizer = new DateRenderInfoTokenizer(pattern);
        Token token = tokenizer.read();

        while (token != null)
        {
            parts.add((DateRenderInfoPart) token.getValue());
            token = tokenizer.read();
        }

        return parts;
    }
}
